﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using PmuRegistry.Silverlight.ModalDialogs;
using PmuRegistry.Silverlight.PmuRegistryDataServiceProxy;
using PmuRegistry.Silverlight.Utilities;
using System.Windows.Data;

namespace PmuRegistry.Silverlight.Pages.Manage
{
	public partial class Measurements : Page
	{
		PhasorDataServiceClient m_client;
		bool m_inEditMode = false;
		string m_signalID = string.Empty;
		int m_deviceID = 0;
		ActivityWindow m_activityWindow;

		public Measurements()
		{
			InitializeComponent();
			Loaded += new RoutedEventHandler(Measurements_Loaded);
			m_client = Common.GetPhasorDataServiceClient();
			m_client.GetDevicesCompleted += new EventHandler<GetDevicesCompletedEventArgs>(client_GetDevicesCompleted);
			m_client.GetSignalTypesCompleted += new EventHandler<GetSignalTypesCompletedEventArgs>(client_GetSignalTypesCompleted);
			//client.GetPhasorsCompleted += new EventHandler<GetPhasorsCompletedEventArgs>(client_GetPhasorsCompleted);
			m_client.GetPhasorsByDeviceCompleted += new EventHandler<GetPhasorsByDeviceCompletedEventArgs>(client_GetPhasorsByDeviceCompleted);
			m_client.GetMeasurementListCompleted += new EventHandler<GetMeasurementListCompletedEventArgs>(client_GetMeasurementListCompleted);
			m_client.SaveMeasurementCompleted += new EventHandler<SaveMeasurementCompletedEventArgs>(client_SaveMeasurementCompleted);
			m_client.GetMeasurementsByDeviceCompleted += new EventHandler<GetMeasurementsByDeviceCompletedEventArgs>(client_GetMeasurementsByDeviceCompleted);
			m_client.GetDeviceByDeviceIDCompleted += new EventHandler<GetDeviceByDeviceIDCompletedEventArgs>(client_GetDeviceByDeviceIDCompleted);
			ButtonClear.Click += new RoutedEventHandler(ButtonClear_Click);
			ButtonSave.Click += new RoutedEventHandler(ButtonSave_Click);
			ListBoxMeasurementList.SelectionChanged += new SelectionChangedEventHandler(ListBoxMeasurementList_SelectionChanged);
			ComboBoxDevice.SelectionChanged += new SelectionChangedEventHandler(ComboBoxDevice_SelectionChanged);			
		}

		void client_GetPhasorsByDeviceCompleted(object sender, GetPhasorsByDeviceCompletedEventArgs e)
		{
			if (e.Error == null)
			{
				ComboBoxPhasorSource.ItemsSource = e.Result;
				if (ComboBoxPhasorSource.Items.Count > 0)
				{
					ComboBoxPhasorSource.SelectedIndex = 0;
					if (ListBoxMeasurementList.SelectedIndex >= 0)
					{
						Measurement selectedMeasurement = ListBoxMeasurementList.SelectedItem as Measurement;
						if (selectedMeasurement.PhasorSourceIndex.HasValue)
						{
							foreach (KeyValuePair<int, string> item in ComboBoxPhasorSource.Items)
							{
								if (item.Value == selectedMeasurement.PhasorLabel)
								{
									ComboBoxPhasorSource.SelectedItem = item;
									break;
								}
							}
						}
						else
							ComboBoxPhasorSource.SelectedIndex = 0;
					}
				}
			}
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Phasors By Device", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}

			if (ComboBoxPhasorSource.Items.Count > 0)
				ComboBoxPhasorSource.SelectedIndex = 0;
		}

		void client_GetDeviceByDeviceIDCompleted(object sender, GetDeviceByDeviceIDCompletedEventArgs e)
		{
			if (e.Error == null)
			{
				Device device = e.Result;
				TextBlockHeading.Text = "Manage Measurements For Device: " + device.Acronym;
			}
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Device Information", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
		}

		void client_GetMeasurementsByDeviceCompleted(object sender, GetMeasurementsByDeviceCompletedEventArgs e)
		{
			if (e.Error == null)
				ListBoxMeasurementList.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Measurements For Device", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (m_activityWindow != null)
				m_activityWindow.Close();
		}
		
        void client_GetMeasurementListCompleted(object sender, GetMeasurementListCompletedEventArgs e)
		{
			if (e.Error == null)
			{
				PagedCollectionView measurementList = new PagedCollectionView(e.Result);
				ListBoxMeasurementList.ItemsSource = measurementList;
				DataPagerMeasurements.Source = measurementList;
				ListBoxMeasurementList.SelectedIndex = -1;
				ClearForm();
			}
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Measurement List", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (m_activityWindow != null)
				m_activityWindow.Close();
		}
		
        void client_SaveMeasurementCompleted(object sender, SaveMeasurementCompletedEventArgs e)
		{
			SystemMessages sm;
			if (e.Error == null)
			{
				ClearForm();
				sm = new SystemMessages(new Message() { UserMessage = e.Result, SystemMessage = string.Empty, UserMessageType = MessageType.Success },
						ButtonType.OkOnly);
			}
			else
			{
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Save Measurement Information", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
			}
			sm.Show();
			
			App app = (App)Application.Current;
			if (m_deviceID > 0)
				m_client.GetMeasurementsByDeviceAsync(m_deviceID);
			else
				m_client.GetMeasurementListAsync();
		}
		
        void ComboBoxDevice_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			KeyValuePair<int, string> selectedDevice = (KeyValuePair<int, string>)ComboBoxDevice.SelectedItem;
			//client.GetPhasorsAsync(selectedDevice.Key, true);
			m_client.GetPhasorsByDeviceAsync(selectedDevice.Key, true);
		}
		
        void ListBoxMeasurementList_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (ListBoxMeasurementList.SelectedIndex >= 0)
			{
				Measurement selectedMeasurement = ListBoxMeasurementList.SelectedItem as Measurement;
				GridMeasurementDetail.DataContext = selectedMeasurement;				
				if (selectedMeasurement.DeviceID.HasValue)
					ComboBoxDevice.SelectedItem = new KeyValuePair<int, string>((int)selectedMeasurement.DeviceID, selectedMeasurement.DeviceAcronym);
				else
					ComboBoxDevice.SelectedIndex = 0;

				if (ComboBoxPhasorSource.Items.Count > 0 && selectedMeasurement.PhasorSourceIndex.HasValue)
				{
					foreach (KeyValuePair<int, string> item in ComboBoxPhasorSource.Items)
					{
						if (item.Value == selectedMeasurement.PhasorLabel)
						{
							ComboBoxPhasorSource.SelectedItem = item;
							break;
						}
					}
				}
				
				ComboBoxSignalType.SelectedItem = new KeyValuePair<int, string>(selectedMeasurement.SignalTypeID, selectedMeasurement.SignalName);

				m_inEditMode = true;
				m_signalID = selectedMeasurement.SignalID;
			}
		}

        void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            Storyboard sb = new Storyboard();
            sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
            sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
            Storyboard.SetTarget(sb, ButtonSaveTransform);
            sb.Begin();

            if (IsValid())
            {
                Measurement measurement = new Measurement();
                measurement.DeviceID = ((KeyValuePair<int, string>)ComboBoxDevice.SelectedItem).Key == 0 ? (int?)null : ((KeyValuePair<int, string>)ComboBoxDevice.SelectedItem).Key;
                measurement.PointTag = TextBoxPointTag.Text.CleanText();
                measurement.AlternateTag = TextBoxAlternateTag.Text.CleanText();
                measurement.SignalTypeID = ((KeyValuePair<int, string>)ComboBoxSignalType.SelectedItem).Key;
                measurement.PhasorSourceIndex = ((KeyValuePair<int, string>)ComboBoxPhasorSource.SelectedItem).Key == 0 ? (int?)null : ((KeyValuePair<int, string>)ComboBoxPhasorSource.SelectedItem).Key;
                measurement.SignalReference = TextBoxSignalReference.Text.CleanText();
                measurement.Adder = TextBoxAdder.Text.ToDouble();
                measurement.Multiplier = TextBoxMultiplier.Text.ToDouble();
                measurement.Description = TextBoxDescription.Text.CleanText();
                measurement.Enabled = (bool)CheckboxEnabled.IsChecked;

                if (m_inEditMode == true && !string.IsNullOrEmpty(m_signalID))
                {
                    measurement.SignalID = m_signalID;
                    m_client.SaveMeasurementAsync(measurement, false);
                }
                else
                    m_client.SaveMeasurementAsync(measurement, true);
            }
        }

        bool IsValid()
        {
            bool isValid = true;

            if (string.IsNullOrEmpty(TextBoxPointTag.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Point Tag", SystemMessage = "Please provide valid Point Tag value.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxPointTag.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (string.IsNullOrEmpty(TextBoxSignalReference.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Signal Reference", SystemMessage = "Please provide valid Signal Reference value.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxSignalReference.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (!TextBoxAdder.Text.IsDouble())
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Adder", SystemMessage = "Please provide valid floating point value for Adder.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxAdder.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (!TextBoxMultiplier.Text.IsDouble())
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Multiplier", SystemMessage = "Please provide valid floating point value for Multiplier.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxMultiplier.Focus();
                                                });
                sm.Show();
                return isValid;
            }
            
            return isValid;
        }
		
        void ButtonClear_Click(object sender, RoutedEventArgs e)
		{
			Storyboard sb = new Storyboard();
			sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
			sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
			Storyboard.SetTarget(sb, ButtonClearTransform);
			sb.Begin();

			ClearForm();
		}
		
        void Measurements_Loaded(object sender, RoutedEventArgs e)
		{
			m_activityWindow = new ActivityWindow("Loading Data... Please Wait...");
			m_activityWindow.Show();

			App app = (App)Application.Current;

			if (this.NavigationContext.QueryString.ContainsKey("did"))
			{
				m_deviceID = Convert.ToInt32(this.NavigationContext.QueryString["did"]);
				m_client.GetMeasurementsByDeviceAsync(m_deviceID);
				m_client.GetDeviceByDeviceIDAsync(m_deviceID);
			}
			else
			{
				m_client.GetMeasurementListAsync();
			}

		}
		
        //void client_GetPhasorsCompleted(object sender, GetPhasorsCompletedEventArgs e)
		//{
		//    //ComboBoxPhasorSource.Items.Clear();
		//    if (e.Error == null)
		//    {
		//        ComboBoxPhasorSource.ItemsSource = e.Result;
		//        if (ComboBoxPhasorSource.Items.Count > 0)
		//            ComboBoxPhasorSource.SelectedIndex = 0;
		//    }
		//    else
		//        MessageBox.Show(e.Error.Message);
		//}
		
        void client_GetSignalTypesCompleted(object sender, GetSignalTypesCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboBoxSignalType.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Signal Types", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}

			if (ComboBoxSignalType.Items.Count > 0)
				ComboBoxSignalType.SelectedIndex = 0;
		}
		
        void client_GetDevicesCompleted(object sender, GetDevicesCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboBoxDevice.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Devices", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboBoxDevice.Items.Count > 0)
				ComboBoxDevice.SelectedIndex = 0;
		}		
		
        void ClearForm()
		{
			GridMeasurementDetail.DataContext = new Measurement();
			ComboBoxDevice.SelectedIndex = 0;			
			//ComboBoxPhasorSource.SelectedIndex = 0;
			ComboBoxSignalType.SelectedIndex = 0;
			m_inEditMode = false;
			m_signalID = string.Empty;
			ListBoxMeasurementList.SelectedIndex = -1;
		}
		
        // Executes when the user navigates to this page.
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			m_client.GetDevicesAsync(DeviceType.NonConcentrator, true);
			m_client.GetSignalTypesAsync(false);			
		}

    }
}
